import { MdlDialogService, MdlSnackbarService } from '@angular-mdl/core';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ProjectService } from 'services/project-service';

import { CompanyService } from '../../../services/company-service';
import { SessionService } from '../../../services/session-service';
import {
    Company,
    Location,
    Role,
    SearchRet
} from '../../../shared/model/defination';
import {
    Building,
    Floor,
    Project,
    Unit
} from '../../../shared/model/defination';

// import { SearchRet } from '../../../services/core/base-generic-service';
type selectedId = {
    project: number;
    building: number;
    floor: number;
    unit: number;
    company?: number;
};

@Component({
    selector: 'app-index',
    templateUrl: './index.component.html',
    styleUrls: ['./index.component.scss'],
    providers: [CompanyService, MdlDialogService, MdlSnackbarService]
})
export class IndexComponent implements OnInit {
    roles: Array<Role> = [];

    public searchRequest: any = {};

    isAdmin: boolean = false;

    selected: selectedId = {
        project: -1,
        building: -1,
        floor: -1,
        unit: -1,
        company: -1
    };

    projects: Array<Project> = [
        {
            name: '加载中',
            locationCode: '23'
        }
    ];

    buildings: Array<Building> = [
        {
            buildingAlias: '加载中...',
            buildingNumber: '1',
            projectId: -1
        }
    ];

    floors: Array<Floor> = [
        {
            buildingId: -1,
            index: '加载中...'
        }
    ];

    units: Array<Unit> = [
        {
            name: '加载中...',
            floorId: 1
        }
    ];

    companies: Array<any> = [
        {
            name: '加载中...'
        }
    ];
    public locationProperties: any;
    public get BuildingId() {
        return +this._route.snapshot.params['buildingId'];
    }
    @ViewChild('confirmAlert') public confirmAlert;
    public count: number = 0;
    public offset: number = 0;
    public limit: number = 10;
    public deleteId: number = 0;
    public isPageLoading: boolean = false;
    public rows = [];
    public pagerMessage = {
        emptyMessage: '没有数据',
        totalMessage: '总计'
    };
    public columns = [
        { name: 'Id', prop: 'id' },
        { name: '公司名称', prop: 'companyName' },
        { name: '电话', prop: 'telephone' },
        { name: '所属楼号', prop: 'companyFloorIds' },
        { name: '所属单元', prop: 'unitCode' }
    ];
    isUserProperty: boolean = this._sessionService.isUserProperty;
    constructor(
        private _route: ActivatedRoute,
        private _router: Router,
        private _companyService: CompanyService,
        private _dialogService: MdlDialogService,
        private _snackService: MdlSnackbarService,
        private _sessionService: SessionService,
        private _projectService: ProjectService
    ) {
        this.roles = this._sessionService.getRoles();
        this.isAdmin = this._sessionService.isUserAdmin;
    }

    get IsRoot() {
        // console.log(this._sessionService.isUserAdmin);
        return this._sessionService.isUserAdmin;
    }

    ParseLocationInfo(locations: Array<Location>) {
        if (!location || locations.length === 0) {
            return '';
        }
        // 目前支持一个location
        // const l = locations[0];
        // return `${l.building.buildingNumber}-${l.floor.index}-${l.unit.name}`;
        return locations
            .map(
                l =>
                    `<span class="multiple-locations">${
                        l.building.buildingNumber
                    }-${l.floor.index}-${l.unit.name}</span>`
            )
            .join('&nbsp');
    }

    async ngOnInit() {
        let resp = await this._projectService
            .getProjectsWithBuildings()
            .toPromise();
        if (this.isUserProperty) {
            delete this.selected.project;
            let projectId = this._sessionService.Managable.id;
            let project = await this._projectService.Get(projectId).toPromise();
            this.projects = [project];
            this.buildings = project.buildings;
            // this.selected.project = project.id;
        } else {
            this.projects = resp.items;
        }
        this.page(this.offset, this.limit);
    }
    async projectChange() {
        this.selected.building = this.selected.floor = this.selected.unit = -1;
        delete this.searchRequest.buildingId;
        delete this.searchRequest.floorId;
        delete this.searchRequest.unitId;
        const project = this.projects.find(p => p.id === this.selected.project);
        project && (this.buildings = project.buildings);
        this.searchRequest.projectId = this.selected.project;
        this.page(0, 10);
    }

    async buildingChange() {
        this.selected.floor = this.selected.unit = -1;
        delete this.searchRequest.floorId;
        delete this.searchRequest.unitId;
        const building = this.buildings.find(
            b => b.id === this.selected.building
        );
        building && (this.floors = building.floors);
        this.searchRequest.buildingId = this.selected.building;
        this.page(0, 10);
    }

    async floorChange() {
        this.selected.unit = -1;
        delete this.searchRequest.unitId;
        const floor = this.floors.find(f => f.id === this.selected.floor);
        floor && (this.units = floor.units);
        this.searchRequest.floorId = this.selected.floor;
        this.page(0, 10);
    }

    async unitChange() {
        const unit = this.units.find(u => u.id === this.selected.unit);
        unit && (this.searchRequest.unitId = this.selected.unit);
        this.searchRequest.unitId = this.selected.unit;
        this.page(0, 10);
    }
    parseProjects(locations: Array<Location>): string {
        return locations.map(l => l.project.name).join(',');
    }
    _constructQuery() {
        let criteria: any = {};
        if (this.searchRequest.projectId) {
            criteria.projectId = this.searchRequest.projectId;
        }
        if (this.searchRequest.buildingId) {
            criteria.buildingId = this.searchRequest.buildingId;
        }
        if (this.searchRequest.floorId) {
            criteria.floorId = this.searchRequest.floorId;
        }
        if (this.searchRequest.floorId) {
            criteria.unitId = this.searchRequest.unitId;
        }
        // if (this._sessionService.isUserProperty) {
        //     criteria.projectId = this._sessionService.Managable.id;
        // }
        // if (this._sessionService.isUserHr) {
        //     criteria.companyId = this._sessionService.Managable.id;
        // }
        return criteria;
    }

    clearFileter() {
        Object.keys(this.selected).forEach(k => (this.selected[k] = -1));
        this.searchRequest = {};
        this.page(0, 10);
    }

    async page(offset, limit) {
        this.isPageLoading = true;

        try {
            let criteria: any = this._constructQuery();
            if (!this.IsRoot) {
                criteria.projectId = this._sessionService.Managable.id;
            }
            criteria.pageNumber = offset + 1;
            criteria.pageSize = this.limit;
            // let action$ = <Observable<SearchRet<Company>>this._companyService.Search(criteria.toJS());
            let action$ = this._companyService.Search(criteria);
            let searchRet: SearchRet<Company> = await action$.toPromise();
            searchRet.items.forEach((r: any) => {
                r.hasCount = r.has_photo_count;
                r.staffCount = r.staffs_count;
            });
            this.count = searchRet.totalPageRecords;

            const start = offset * limit;
            const end = start + limit;
            const rows = [...this.rows];

            for (let i = start; i < end; i++) {
                rows[i] = searchRet.items[i - start];
            }
            // this.rows = rows;
            this.rows = searchRet.items;
            console.log('Page Results', start, end, rows);
        } catch (e) {
            console.log(e);
            if (e.status === 401) {
                this._router.navigate(['/login']);
            }
        } finally {
            this.isPageLoading = false;
        }
    }

    async delete(id) {
        try {
            await this._dialogService
                .confirm(
                    '警告，删除公司会删除公司下的所有管理员和用户，确定删除此公司？',
                    '取消',
                    '确认'
                )
                .toPromise();
            await this._companyService.Delete(+id).toPromise();
            await this.ngOnInit();
        } catch (e) {
            this._snackService.showToast((e as any).message);
        } finally {
        }
    }

    onPage(event) {
        console.log('Page Event', event);
        this.page(event.offset, event.limit);
    }
}
